package crawler.cnki.utils;

import crawler.cnki.selenium.FileUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.UUID;

public class DownloadFileUtils {
    public static String download(String url,String fileName){
        ChromeOptions chromeOptions = new ChromeOptions();
        //无头浏览器
        chromeOptions.addArguments("headless");
        chromeOptions.addArguments("disable-gpu");
        chromeOptions.addArguments("no-sandbox");
        chromeOptions.addArguments("disable-dev-shm-usage");
        //设置默认下载路径
        HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory", FileUtil.getCommonProp("download.default_directory"));
        chromeOptions.setExperimentalOption("prefs",chromePrefs);
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get(url);
        driver.findElement(By.cssSelector("input#user_login")).sendKeys("leo345");
        driver.findElement(By.cssSelector("input#user_password")).sendKeys("Leo6688671");
        driver.findElement(By.cssSelector("input.btn")).click();
        driver.get(url);
        driver.quit();
        String path=FileUtil.getCommonProp("download.default_directory")+"\\";
        File oldFile = new File(path+fileName);
        String newPath=path+ UUID.randomUUID()+".pdf";
        File newFile = new File(newPath);
        if(oldFile.exists()&&oldFile.isFile())
            oldFile.renameTo(newFile);
        return newPath;
    }
}
